<template>
  <div class="page store-manage">
    <div class="scroll-view">
      <customHeader
        middleTitle="门店管理"
        v-if="authCreateShop"
        rightTitle=""
        @rightCallBack="addStore"
      />
      <!-- <customHeader middleTitle="门店管理" v-if="authCreateShop" @leftCallBack="handleBack"/> -->
      <customHeader middleTitle="门店管理" v-else @leftCallBack="handleBack" />
      <searchBar @search="searchCallbck" />
      <div class="page-body">
        <div class="section" ref="wrapper" :style="{ height: '100%'}">
          <no-data msg="暂无数据" v-if="!loading&&list.length==0"></no-data>
          <ul
            class="store-list"
            v-infinite-scroll="loadMore"
            infinite-scroll-disabled="loading"
            infinite-scroll-distance="30"
          >
            <li v-for="item in list" :key="item.id">
              <div class="top" @click="ToDetail(item.id,item.deleteFlg)">
                <div class="left">
                <img class="shop-head" :src="imgFormate(item.mainImage)" alt="">
                </div>
                <div class="right">
                  <div class="store-name">
                    <span>{{item.shopName}}</span>
                    <i class="zhk-list_rarrow"></i>
                  </div>
                  <ul class="pay-way">
                    <li :class="item.alipay.class">
                      <i class="zhk-detail_zfb"></i>
                    </li>
                    <li :class="item.wcpay.class">
                      <i class="zhk-detail_wx"></i>
                    </li>
                    <li :class="item.cloudPay.class">
                      <i class="zhk-detail_ysf"></i>
                    </li>
                    <li :class="item.unionpay.class">
                      <i class="zhk-detail_yl"></i>
                    </li>
                  </ul>
                  <div class="store-status" :class="item.auditStatusDes.class">{{item.auditStatusDes.val}}</div>
                </div>
              </div>
              <ul class="link-wrap">
                <li>
                  <template v-if="item.shopCodeTypeList">
                    <div v-if="item.shopCodeTypeList.includes(2)" @click="ToStoreCode(2, item)">支付宝门店码</div>
                    <div v-if="item.shopCodeTypeList.includes(5)" @click="ToStoreCode(5, item)">微信门店码</div>
                  </template>
                  <!-- <div @click="applyWallet(item)" v-if="item.hasWalletShow == 1 && item.walletStatus == 0">开通钱包</div>
                  <div @click="openWallet(item)" v-if="item.hasWalletShow == 1 && item.walletStatus == 1">进入钱包</div>
                  <div @click="applyWalletDetail(item)" v-if="item.hasWalletShow == 1 && item.walletStatus == 2">资料审核中</div>
                  <div @click="applyWalletDetail(item)" v-if="item.hasWalletShow == 1 && item.walletStatus == 3">资料审核中</div> -->
                  <div @click="ToQrCode(item.id,item.shopName)">收款二维码</div>
                  <div @click="ToAccountManage(item)" v-if="isShowAccountManage(item)">收款账户管理</div>
                </li>
              </ul>
            </li>
          </ul>
          <p v-show="loading" class="page-infinite-loading">
            <mt-spinner :style="{display:'inline-block'}" type="fading-circle"></mt-spinner>
          </p>
          <div v-show="noMore&&!loading&&list.length!==0" class="no-more">
            <span>已经全部加载完毕</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import searchBar from "../../components/searchBar/searchBar";
import config from "../../base/profile/config.json";
import jsBridge from "../../tools/jsBridge.js";
import jsAuthority from "../../tools/jsAuthority.js";
import { Toast, MessageBox } from "mint-ui";
import localStorageClient from "../../js/localstorage.js";
import noData from "../../components/noData/noData";
export default {
  name: "storeManage",
  data() {
    return {
      authCreateShop: false,
      loading: false,
      keywords: "",
      nextPage: 1,
      dictAuditStatus: {//门店状态
        "1": { class: "green", val: "审批中" },
        "2": { class: "green", val: "变更审批中" },
        "3": { class: "red", val: "审批驳回" },
        "4": { class: "red", val: "变更审批驳回" },
        "5": { class: "grey", val: "审批通过" },
        "6": { class: "grey", val: "变更审批通过" }
      },
      dictPayTips: {
        //支付方式开通状态(0:未开通,1:已开通,2:已冻结),3申请中 4已关闭,5开通失败
        "0": { class: "unopen", val: "未开通" },
        "1": { class: "", val: "已开通" },
        "2": { class: "unopen", val: "已冻结" },
        "3": { class: "unopen", val: "审核中" },
        "4": { class: "unopen", val: "未开通" },
        "5": { class: "unopen", val: "开通失败" }
      },
      noMore: false,
      list: [],
    };
  },
  methods: {
    //是否显示【开通收款账户】按钮（规则：1审批中、审批驳回状态的门店不显示;2微信、支付宝都没有提交过进件） 全部都是已关闭4则显示
    isShowOpenAccount(item) {
      if (item.auditStatus !== 1 && item.auditStatus !== 3) {
        if ((item.wechatPayStatus == "0" && item.alipayPayStatus == "0") || (item.wechatPayStatus == "4" && item.alipayPayStatus == "4")) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    //是否显示【收款账户管理】按钮（规则：审批中、审批驳回状态的门店不显示;2微信、支付宝微信、支付宝有1个或多个提交过进件） 只有一个是已关闭4则显示
    isShowAccountManage(item) {
      if (
        item.auditStatus !== 1 &&
        item.auditStatus !== 3
        // &&
        // (item.wechatPayStatus != "0" || item.alipayPayStatus != "0") &&
        // (item.wechatPayStatus != "4" || item.alipayPayStatus != "4")
      ) {
        return true;
      } else {
        return false;
      }
    },
    //是否显示支付宝、微信的开通状态（规则：审批中、审批驳回状态的门店不显示）
    isShowPayStatus(auditStatus) {
      if (auditStatus !== 1 && auditStatus !== 3) {
        return true;
      } else {
        return false;
      }
    },
    getPayTips(state) {
      //获取支付渠道的显示文字
      var tips = this.dictPayTips[state];
      if (tips === undefined) {
        tips = { class: "", val: "--" };
      }
      return tips;
    },
    loadData(page) {
      if(this.loading){
        return;
      }
      this.loading = true;
      if (page == undefined) {
        page = 1;
      }
      var url = "/newapp/shop/getShopList.do?currentPage=" + page + "&pageSize=10";
      if (this.keywords !== "" && this.keywords.length > 0) {
        url += "&keywords=" + this.keywords;
      }

      this.ajax({
        url: url,
        type: "get",
        controlLoading: false
      })
        .then((res) => {
        
          this.loading = false;
          this.noMore = false;
          if (res.success) {
            const data = res.resultObject;
            //最后一页将noMore设置为true
            if (data != null && JSON.stringify(data) != "{}") {
              if (data.nextPage > page) {
                this.nextPage = data.nextPage;
              } else {
                this.noMore = true;
              }
              this.bindData(data.pageData);
            } else {
              this.noMore = true;
            }
          } else {
            this.noMore = true;
          }
        })
        .catch((err) => {
          this.loading = false;
          this.noMore = true;
        });
    },
    bindData(data) {
  
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        const auditStatusDes = this.dictAuditStatus[item.auditStatus];
        item["wechatPayStatus"] = item["wechatPayStatus"] ? item["wechatPayStatus"] : "0";
        item["alipayPayStatus"] = item["alipayPayStatus"] ? item["alipayPayStatus"] : "0";
        item["unionpay"] = item["unionpay"] ? item["unionpay"] : "0";
        item["cloudPayStatus"] = item["cloudPayStatus"] ? item["cloudPayStatus"] : "0";
        item["mainImage"] = item["mainImage"]&&item["mainImage"].length>0 ? item["mainImage"][0] : "";
        this.list.push({
          supplierId: item.supplierId,
          id: item["shopId"],
          shopName: item["shopName"],
          alipay: this.getPayTips(item["alipayPayStatus"]),
          wcpay: this.getPayTips(item["wechatPayStatus"]),
          unionpay: this.getPayTips(item["unionpay"]),
          cloudPay: this.getPayTips(item["cloudPayStatus"]),
          wechatPayStatus: item["wechatPayStatus"],
          alipayPayStatus: item["alipayPayStatus"],
          unionPayStatus: item["unionpay"],
          cloudPayStatus: item["cloudPayStatus"],
          auditStatus: item["auditStatus"],
          auditStatusDes: auditStatusDes,
          deleteFlg: item["deleteFlg"],
          mainImage:item["mainImage"],
          shopCodeTypeList: item.shopCodeTypeList || null,
          hasWalletShow: item.hasWalletShow,
          walletStatus: item.walletStatus,
          walletUserId: item.walletUserId
        });
      }
    },
    //根据支付状态显示不同的支付样式
    payStatus(status) {
      let className = { "": true };
      if (status == "未开通") {
        className = { unopen: true };
      } else if (status == "审核失败") {
        className = { fail: true };
      } else {
        className = "";
      }
      return className;
    },
    //跳转添加门店
    addStore() {
      this.$router.push({
        path: "/storeManage/editStore",
        query: { type: 1 }
      });
    },
    //跳转门店详情
    ToDetail(id, delFlag) {
      var flag = delFlag ? "1" : "0";
      this.$router.push({
        path: "/storeManage/storeDetails",
        query: { id: id, delFlag: flag }
      });
    },
    //支付宝门店码
    ToStoreCode(type, item) {
      this.$router.push({
        path: "/storeManage/getMoneyQrCode",
        query: { supplierId: item.supplierId, shopId: item.id, shopName: item.shopName, codeType: type }
      });
    },
    //开通钱包
    applyWallet(item) {
      let params =  {supplierId: item.supplierId, shopId: item.id};
      var url = "/app/shop/hasOpenWallet.do";
      this.ajax({
        url: url,
        type: "post",
        data: params,
        controlLoading: true
      })
      .then((res) => {
        if (res.success) {
          jsBridge.gotoWallet({walletId: item.walletUserId});
        }
        else {
          MessageBox.alert(res.msg);
        }
      })
      .catch((err) => {
        Toast("开通钱包失败，请稍后再试");
      });
    },
    //打开钱包
    openWallet(item) {
      jsBridge.gotoWallet({walletId: item.walletUserId});
    },
    //申请钱包详情
    applyWalletDetail(item) {
      item.auditStatus = item.walletStatus == 2 ? 1 : 3;
      item.auditDesc = '';
      item.walletUserId = item.merchantId;
      this.$router.push({ path: "/splitBill/processResult", query: {shopInfo: item}});
    },
    //跳转收款二维码
    ToQrCode(shopId, shopName) {
      let authList = false;
      jsAuthority.checkedSuccess(() => {
        authList = jsAuthority.checked(
          "app.shop.gather_qrcode.list"
        );
      });
      if (!authList) {
        Toast("暂无该权限");
        return;
      }
      this.$router.push({
        path: "/storeManage/getMoneyQrCode",
        query: { shopId: shopId, shopName: shopName }
      });
    },
    //跳转收款账户管理
    ToAccountManage(item) {
      //验证是否在进件中
      // if (item && item["wechatPayStatus"] == "3") {
      //   MessageBox.alert("进件审批中，暂不支持操作。");
      //   return false;
      // }
      this.$router.push({
        path: "/storeManage/gatheringManage",
        query: { shopId: item.id }
      });
    },
    //跳转进件
    ToOpenShroffAccount(item) {
      //验证是否在进件中
      if (item && item["wechatPayStatus"] == "3") {
        MessageBox.alert("进件审批中，暂不支持操作。");
        return false;
      }
      const smsCache = localStorageClient.load("sms", 120); //data.merchantStatus == constants.store.WEIXIN_PAY_STATUS.none
      const merchantStatus = item.wechatPayStatus;
      if (smsCache) {
        this.$router.push({
          path: "/storeManage/openShroffAccount",
          query: { shopId: item.id }
        });
      } else {
        this.$router.push({
          path: "/SMSVerification",
          query: { nextPath: "/storeManage/openShroffAccount", shopId: item.id }
        });
      }
    },
    //无限加载
    loadMore() {
      if (this.loading || this.noMore) {
        return;
      }
      this.loadData(this.nextPage);
    },
    //搜索
    searchCallbck(value) {
      //搜索方法
      this.list = [];
      this.noMore = true;
      this.keywords = value;
      this.loadData(1);
    },
    imgFormate(v) {
      return config.previewUrlPrefix + v;
    },
  },
  created() {
    jsAuthority.checkedSuccess(() => {
      this.authCreateShop = jsAuthority.checked("app.me.shopmanage.list.add");
    });
  },
  components: {
    customHeader,
    searchBar,
    noData
  }
};
</script>

<style lang='scss' scoped>
@import "storeManage";
</style>
